package service;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import util.IDUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class DbRealmService <T extends Model> {

    public Class<T> clazz;
    public T m;

    public DbRealmService(){
        Type superclass = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = null;
        if (superclass instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) superclass;
            Type[] typeArray = parameterizedType.getActualTypeArguments();
            if (typeArray != null && typeArray.length > 0) {
                clazz = (Class<T>) typeArray[0];
                try {
                    m= clazz.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public T getDataById(String id){
        return (T) m.findById(id);
    }

    public Page<T> getDatasByPage(int page, int size){
        return m.paginate(page,size,"select *","from "+m.getClass().getSimpleName());
    }

    public boolean addData(T m){
        m.set("id", IDUtil.getRandomID());
        return m.save();
    }

    public boolean deleteDataById(String id){
        return m.deleteById(id);
    }

    public boolean updateData(T m){
        return m.update();
    }
}
